<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\product\Cart;
use app\admin\model\product\Category;
use app\admin\model\product\Lists;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\common\controller\Api;
use think\Controller;
use think\Db;
use think\Request;


class Productcart extends Api
{
    private static $model;
//    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Cart();
    }

    /**
     * 购物车列表
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $pageSize = input('page_size', 15);
        $mark = input('type', '');

        $userId = $this->auth->id;
        $where = [
            'user_id' => $userId
        ];

        if ($mark) {
            $map['mark'] = $mark;
        }

        $list = self::$model->where($where)->order('createtime desc')->paginate($pageSize);
        if ($list) {
            foreach ($list as $val) {
                $val->lists->image = make_full_url($val->lists->image);
                $attrs = $this->get_attrs($val->sku_id);
                $val->attrs = $attrs;
            }
        }
        $this->success('购物车', $list);
    }

    /**
     * 加入购物车
     */
    public function create()
    {
        $skuId = input('sku_id');
        $number = input('number');
        if (!$skuId || !$number) {
            $this->error('参数缺失！');
        }

        $skuInfo = Sku::find($skuId);
        if (!$skuInfo) {
            $this->error('该商品规格不存在！');
        }

        if ($skuInfo->stock < $number) {
            $this->error('该规格商品余额不足！');
        }

        $userId = $this->auth->id;
        $cdata = [
            'user_id' => $userId,
            'product_id' => $skuInfo->product_id,
            'sku_id' => $skuId,
        ];

        $row_info = self::$model->where($cdata)->find();
        if (!$row_info) {
            $cateId = Lists::where('id', $skuInfo->product_id)->value('category_id');
            $mark = Category::where('id', $cateId)->value('mark');
            $cdata['price'] = $skuInfo->price;
            $cdata['number'] = $number;
            $cdata['mark'] = $mark;
            $ret = self::$model->create($cdata);
        } else {
            $ret = self::$model->where('id', $row_info->id)->setInc('number', $number);
        }

        if (!$ret) {
            $this->error('加入失败！');
        }

        $this->success('加入成功！');
    }

    /**
     * 删除购物车商品
     */
    public function del()
    {
        $ids = input('ids');
        if (!$ids) {
            $this->error('参数缺失！');
        }

        $ids = trim($ids, ',');
        $ret = self::$model->where('id', 'in', $ids)->delete();
        if (!$ret) {
            $this->error('删除失败！');
        }

        $this->success('删除成功');
    }
}
